<?php

namespace app\api\controller;

use app\api\model\Order;
use app\common\controller\Api;
use fast\Http;
use fast\Random;
use think\Db;
use think\Log;
use app\api\model\Deal as DealModel;

/**
 * 定时任务接口
 */ 
class Cron extends Api
{

    protected $noNeedLogin = ['mill_pro','deal_order','lists','change_config','equity','addpeople','setcommon','getuserid','getuid','deluser'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 入口文件
     */
    public function lists()
    {
        //$time = time();
        //if ($time >= strtotime(date('22:00')))
       // {
           // $mill_pro = 'https://cny.it8851.com/api/cron/mill_pro';
           // Http::get($mill_pro);
           // Http::get($mill_pro);
           // Http::get($mill_pro);
           // Http::get($mill_pro);
        //}

        //Http::get('https://cny.it8851.com/api/cron/deal_order');

    }
  	public function setcommon(){
        //CommonPasswd
        $data['value'] = rand(100000,999999);
        $r = db('config')->where(['name'=>'CommonPasswd'])->update($data);
        if($r){
            $this->success('设置成功');
        }else{
            $this->error('设置失败');
        }
    }
    /**
     * 投资产币
     */
    public function equity(){
        //超过晚上22点开始产币
        $shi = '22:00';
        $time = time();
        $today_time = strtotime(date('Y-m-d')); //  今天0点时间戳
        $tom_time = $today_time + 86400;  //  明天时间戳

        //  每天分红时间
        if ($time < strtotime(date($shi)))
        {
            $this->error('分红时间没到');
        }
        $us = new \app\api\model\User();
        //查询操作时间在10点之前的 并且正在运行的
        $where['caotime'] = ['<',strtotime(date($shi))];
        $where['status'] = 1;
        $list = db('user_equity')->where($where)->limit(30)->select();
        if($list){
            foreach($list as $k=>$v){
                //查询该用户信息
                $user = $us->where('id','=',$v['user_id'])->find();
                // $user = db('user')->field('id,first,second')->where(['id'=>$v['user_id']])->find();
                //开始产币  
                //得到基金信息
                $equity = db('equity')->where(['id'=>$v['equity_id']])->find();
                $equity['earnings'] = $equity['earnings']/48;
                //计算从最后一次操作到现在有多少个30分钟
                $min = floor((time()-$v['caotime'])/(30*60));
                //$min = 1;
                //计算产多少币
                $coin = $v['money']*$equity['earnings']*$min;
                //加入产币表
                $data['user_id'] = $v['user_id'];
                $data['equity_user_id'] = $v['id'];
                $data['equity_id'] = $v['equity_id'];
                $data['money'] = $coin;
                $data['addtime'] = time();
                $data['num'] = $v['money'];
                db('equity_cny')->insert($data);
                //修改产币时间
                db('user_equity')->where(['id'=>$v['id']])->update(['caotime'=>time()]);
                //增加产币金额
                db('user_equity')->where(['id'=>$v['id']])->setInc('money',$coin);
                db('user_equity')->where(['id'=>$v['id']])->setInc('c_money',$coin);
                //给上级返利
                $this->get_fee_divide($user,$coin,($v['money']-$v['c_money'])/500);
            }
            $this->success('产币成功',$list);
        }else{
            $this->success('暂无产币');
        }
        
    }
    //  获取基金利润分成
    private function get_fee_divide($user,$sac,$num)
    {
        $us = new \app\common\model\User();
        $first = config('site.first_fee_reward') / 100; //第一代分红比例
        $sec = config('site.second_fee_reward') / 100; //第二代分红比例
        $third = config('site.third_fee_reward') / 100; //第三代分红比例
        $first_num = config('site.first_profits_neednum'); //第一代推荐人有效人数
        $sec_num = config('site.second_profits_neednum'); //第二代推荐人有效人数
        $third_num = config('site.third_profits_neednum'); //第三代推荐人有效人数
        $num1 = 5; //第一代股数
        $num2 = 10; //第二代股数
        $num3 = 20; //第三代股数

        if ($user->first)
        {
            //判断第一级人拿的股权数
            $a = db('user_equity')->where(['user_id'=>$user->first,'status'=>1])->find();
            if(($a['money']/500)>=$num1){
                $divide = $sac * $first;
                $sup = \app\common\model\User::get($user->first);
                if ($sup)
                {
                    $sup->save(['cny' => $sup->cny + $divide]);
                    account_log($sup->id,$divide,$sup->cny + $sup->freeze_cny,0,$sup->sac+$sup->freeze_sac,'用户ID '.$user->id.' 基金利润分成','','','',2);
                }
            }
        }

        if ($user->second)
        {
            $a = db('user_equity')->where(['user_id'=>$user->second,'status'=>1])->find();
            if(($a['money']/500)>=$num2){
                $divide = $sac * $sec;
                $sup = \app\common\model\User::get($user->second);
                if ($sup)
                {
                    $sup->save(['cny' => $sup->cny + $divide]);
                    account_log($sup->id,$divide,$sup->cny + $sup->freeze_cny,0,$sup->sac+$sup->freeze_sac,'用户ID '.$user->id.' 基金利润分成','','','',2);
                }
            }
        }

        if ($user->third)
        {
            $a = db('user_equity')->where(['user_id'=>$user->third,'status'=>1])->find();
            if(($a['money']/500)>=$num3){
                $divide = $sac * $third;
                $sup = \app\common\model\User::get($user->third);
                if ($sup)
                {
                    $sup->save(['cny' => $sup->cny + $divide]);
                    account_log($sup->id,$divide,$sup->cny + $sup->freeze_cny,0,$sup->sac+$sup->freeze_sac,'用户ID '.$user->id.' 基金利润分成','','','',2);
                }
            }
        }

    }
    /**
     * 矿机生产
     */
    public function mill_pro()
    {

        //当前时间往前推30分钟
        $time = time();
        $last_time = $time-30*60;
        // $today_time = strtotime(date('Y-m-d')); //  今天0点时间戳
        // $tom_time = $today_time + 86400;  //  明天时间戳

        // //  每天分红时间
        // if ($time < strtotime(date('22:00')))
        // {
        //     $this->error('分红时间没到');
        // }

        //  先查询出来需要返币的用户矿机列表
        $mill_where = [
            'status' => ['=',1],
            'last_time'     =>  ['<' ,  $last_time],
        ];

        $mill_list = Db::name('user_mill')
            ->where($mill_where)
            ->limit(0,100)
            ->order('buy_time','desc')
            ->select();

        if (!$mill_list)
        {
            $this->success('所有矿机返币完成');
        }

        //
        $us = new \app\api\model\User();
        $sac_price  = $this->get_sac_price();
        //  遍历每条数据
        foreach ($mill_list as $mill)
        {
            $uid        = intval($mill['user_id']);
            $period     = $mill['total_days'];  //  运行周期/天数
            $per_earn   = $mill['earnings'] / ($period*24*2);                          //  每30分钟应获取收益（钱）
                                           //  获取sac价格
            $sac   = round($per_earn / $sac_price,4);         //  每天应返SAC数


            //  矿机列表数据
            $mill_update_data = [
                'last_time'     =>  $time,
                'earnings_yet'  =>  $mill['earnings_yet'] + $per_earn,
                'sac'           =>  $mill['sac'] + $sac,
                'period'        =>  $mill['period'] + (1/48),
            ];
            if($mill['last_time']){
                if ($mill['last_time']+30*60 >= $mill['end_time'])
                {
                    //  如果今天是最后一次返币
                    $mill_update_data['status'] = config('MillStatus.close');
                }
            }


            //  用户资金记录表数据

            $user = $us->where('id','=',$uid)->find();
            if (!$user)
            {
                Log::error('矿机对应用户不存在：'.json_encode($mill));
                continue;

            }

            //  用户数据
            $user->sac += $sac;
            //  事务提交
            Db::startTrans();
            try{
                //$millname = Db::name('mill')->where('id','=',$mill['id'])->find()['mill_name'];
                $this->get_divide($user,$sac,$mill['id']);
                account_log($uid,0,$user->cny + $user->freeze_cny,$sac,$user->sac+$user->freeze_sac,"用户ID ".$uid." 产sac ". $sac. " 个",'','','',1,$mill['id']);
                $user->save();
                Db::name('user_mill')->where('id','=',$mill['id'])->update($mill_update_data);
                Db::commit();
            }
            catch (\Exception $e)
            {
                Db::rollback();
                Log::error('矿机产币事务出错了：'.$e);
            }
        }
        //  写入日志完成提交
        $result = ['mill_list' => $mill_list,'time' => '矿机产币时间：'.date('Y-m-d H:i:s',$time)];
        trace(json_encode($result),'cron');
        $this->success($result);
    }


    //  获取分成
    private function get_divide($user,$sac,$user_mill)
    {
        $us = new \app\common\model\User();
        $first = config('site.first_profits_reward') / 100;
        $sec = config('site.second_profits_reward') / 100;
        $third = config('site.third_profits_reward') / 100;
        $first_num = config('site.first_profits_neednum');
        $sec_num = config('site.second_profits_neednum');
        $third_num = config('site.third_profits_neednum');

        if ($user->first && $us->where(['first' => $user->first,'is_buymill'=>1])->count() >= $first_num)
        {
            $divide = $sac * $first;
            $sup = \app\common\model\User::get($user->first);
            if ($sup)
            {
                $sup->save(['sac' => $sup->sac + $divide]);
                account_log($sup->id,0,$sup->cny + $sup->freeze_cny,$divide,$sup->sac+$sup->freeze_sac,'用户ID '.$user->id.' 矿机产币分成','','','',2,$user_mill);
            }
        }

        if ($user->second && $us->where(['first' => $user->second,'is_buymill'=>1])->count() >= $sec_num)
        {
            $divide = $sac * $sec;
            $sup = \app\common\model\User::get($user->second);
            if ($sup)
            {
                $sup->save(['sac' => $sup->sac + $divide]);
                account_log($sup->id,0,$sup->cny + $sup->freeze_cny,$divide,$sup->sac+$sup->freeze_sac,'用户ID '.$user->id.' 矿机产币分成','','','',2,$user_mill);
            }
        }

        if ($user->third && $us->where(['first' => $user->third,'is_buymill'=>1])->count() >= $third_num)
        {
            $divide = $sac * $third;
            $sup = \app\common\model\User::get($user->third);
            if ($sup)
            {
                $sup->save(['sac' => $sup->sac + $divide]);
                account_log($sup->id,0,$sup->cny + $sup->freeze_cny,$divide,$sup->sac+$sup->freeze_sac,'用户ID '.$user->id.' 矿机产币分成','','','',2,$user_mill);
            }
        }

    }

    private function get_sac_price()
    {
        $data = Http::get(config('sac_url'));
        $data = json_decode($data, true);
        //dump($data);die;
        $price = end($data['price_usd'])[1];        //比特币
        $rate = config('site.rate');
        $sacprice = config('site.localprice');
        return $sacprice;
    }



    //处理封号和付币的状态
    public function deal_order()
    {
        $time = time() - 12*3600;
        $orderModel = new Order();
        $userModel = new \app\admin\model\User();
        $dealModel = new \app\admin\model\Deal();
        $where = [
            'status' => ['in','1,2'],
            'create_time' => ['<',$time]
        ];
        $orders = $orderModel           //查询出所有超过24小时的撮合订单
            ->where($where)
            ->select();
//        $this->success('',$orders);exit;
        foreach($orders as $value)
          
        {
            if($value->status == '1'){      //如果是未付款的订单
//                $this->success('',$value);exit;
                Db::startTrans();
                try{
                    $userModel->save(['status'=>'hidden'],['id'=>$value->buy_user_id]); //直接冻结用户
                  //    db('user')->where(['id'=>$value->buy_user_id])->update(['status'=>'hidden']);
                    $sale_deal = $dealModel->where('deal_sn',$value->sale_deal_sn)->find(); //查询出来卖家交易的cny
                    $sale_deal->residue_cny += $value->cny;                             //把cny返给挂单继续交易
                    $sale_deal->status = 1;                                             //交易表状态改为未匹配
                    $sale_deal->match_time = 0;                                         //匹配时间改为0
                    $sale_deal->create_time = time();
                    $sale_deal->save();
                    $buy_deal = $dealModel->where('deal_sn',$value->buy_deal_sn)->find();
                    $buy_deal->status = 0;
                    $buy_deal->save();
                    $orderModel->where('sale_deal_sn',$value->sale_deal_sn)->delete();      //删除订单表
                    Db::commit();
                }
                catch (\Exception $e)
                {
                    Db::rollback();
                    Log::error('未付款封号出错了：'.$e);
                }
            }
            if($value->status == '2')   //如果是未付币的订单
            {
//                $this->success('',$value);exit;
              Db::startTrans();
                try{
                    $userModel->save(['status'=>'hidden'],['id'=>$value->buy_user_id]); //直接冻结用户
                    //db('user')->where(['id'=>$value->buy_user_id])->update(['status'=>'hidden']);
                    $sale_deal = $dealModel->where('deal_sn',$value->sale_deal_sn)->find(); //查询出来卖家交易的cny
                    $sale_deal->residue_cny += $value->cny;                             //把cny返给挂单继续交易
                    $sale_deal->status = 1;                                             //交易表状态改为未匹配
                    $sale_deal->match_time = 0;                                         //匹配时间改为0
                    $sale_deal->create_time = time();
                    $sale_deal->save();
                    $buy_deal = $dealModel->where('deal_sn',$value->buy_deal_sn)->find();
                    $buy_deal->status = 0;
                    $buy_deal->save();
                    $orderModel->where('sale_deal_sn',$value->sale_deal_sn)->delete();      //删除订单表
                    Db::commit();
                }
                catch (\Exception $e)
                {
                    Db::rollback();
                    Log::error('未付款封号出错了：'.$e);
                }
              /*
                Db::startTrans();               //模拟确认付币
                try{
                    $order_info = $value;
                    $user = \app\admin\model\User::get($order_info->sale_user_id);
                    $buy_user =  \app\admin\model\User::get($order_info->buy_user_id);

                    $buy_user_update = [
                        'cny'       =>  $buy_user->cny + $order_info->cny,
                        'total_cny' =>  $buy_user->total_cny + $order_info->cny
                    ];
                    $order_info->save(['status' => config('OrderStatus.Finished'),'complete_time' => time()]);    //  更新当笔交易状态
                    $user->save(['freeze_cny' => $user->freeze_cny - $order_info->cny]);    //  更新卖家币数
                    $buy_user->save($buy_user_update);  //  更新买家币数
                    //  记录资金流动
                    account_log($user->id,'',$user->cny + $user->freeze_cny,0,$user->sac,'卖家ID'.$user->id.'确认付币'.$order_info->cny,$order_info->cny * -1,$order_info->sale_deal_sn);
                    account_log($buy_user->id,$order_info->cny,$buy_user->cny + $buy_user->freeze_cny,0,$buy_user->sac,'买家ID'.$buy_user->id.'收币'.$order_info->cny,'',$order_info->buy_deal_sn);
                    //  判断是否修改交易标状态
                    $deal_finish_status = ['status' => config('DealStatus.Finished'),'complate_time' => time()];

                    //  查找是否还有未完成记录
                    $buy_finished = $orderModel->where([
                        'buy_deal_sn' => $order_info->buy_deal_sn,
                        'status' => ['<>', config('OrderStatus.Finished')]
                    ])->find();
                    $sale_finished = $orderModel->where([
                        'sale_deal_sn'  =>  $order_info->sale_deal_sn,
                        'status'    =>  ['<>' , config('OrderStatus.Finished')]
                    ])->find();
                    if (empty($buy_finished))
                    {
                        $deal_info = DealModel::get(['deal_sn' => $order_info->buy_deal_sn]);
                        if($deal_info && $deal_info->residue_cny <= 0){
                            $deal_info->save($deal_finish_status);
                        }
                    }
                    if (empty($sale_finished))
                    {
                        $deal_info = DealModel::get(['deal_sn' => $order_info->sale_deal_sn]);
                        if($deal_info && $deal_info->residue_cny <= 0){
                            $deal_info->save($deal_finish_status);
                        }
                    }
                    //  确认付币给买家发送短信
                    send_common_sms($buy_user->mobile,$order_info->order_sn,'已成功交易');
                    send_common_sms($user->mobile,$order_info->order_sn,'已成功交易');   //  卖家点确认卖家发送信息
                    Db::commit();
                }
                catch (\Exception $e)
                {
                    Db::rollback();
                    Log::error('到时间确认付币出错了：'.$e);
                }
                */
            }
        }
        $result = ['orders'=>$orders,'time'=>'封号和付币'.date('Y-m-d H:i:s',$time)];
        trace($result,'deal_order');
        $this->success($result);
    }

    //  修改配置文件
    public function change_config()
    {
        //var_export(config('site'));
        $randpwd = Random::nozero(8);

        $config = [];
        foreach (model('config')->all() as $k => $v) {

            $value = $v->toArray();
            if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                $value['value'] = explode(',', $value['value']);
            }
            if ($value['type'] == 'array') {
                $value['value'] = (array)json_decode($value['value'], TRUE);
            }
            if ($value['name'] == 'CommonPasswd')
            {
                $config[$value['name']] = $randpwd;
                continue;
            }
            $config[$value['name']] = $value['value'];
        }
        //dump($config);
        file_put_contents(APP_PATH . 'extra' . DS . 'site.php', '<?php' . "\n\nreturn " . var_export($config, true) . ";");
        echo 'refresh on '.date('Y-m-d H:i:s');
    }
    /**
     * 增加虚拟人物
     */
   public function addpeople(){
        $first = input('first');
        $num = input('num');
        $second = input('second');
        for ($i=0; $i < $num; $i++) { 
           $data['id'] = rand(100000,999999);
            $data['username'] = rand(100000000,9999999999).'@qq.com';
            $data['nickname'] = 'ceshi'.rand(10000,99999);
            $data['password'] = '42a318e0e16802323cf71655f5cff90f';
            $data['salt'] = 'S07spJ';
            $data['mobile'] = '187'.rand(10000000,99999999);
            $data['createtime'] = time();
            $data['jointime'] = time();
            $data['status'] = 'normal';
            //$data['first'] = '524396';
            //$data['first'] = '597843';
            $data['first'] = $first;
            $data['second'] = $second;
            $data['is_buymill'] = 1;
            db('user')->insert($data);
        }
        
    }
   public function getuserid(){
        $user_id = input('user_id');
        $user = db('user')->whereOr(['first'=>$user_id])->whereOr(['second'=>$user_id])->whereOr(['third'=>$user_id])->select();
       	foreach($user as $k=>$v){
          $id[] = $v['id']; 
        }
     	$id = implode(',', $id);
     	echo $id;
     	//dump($id) ;
    }
  	public function getuid(){
        $user_id = input('user_id');
        $where['father_id'] = ['like','%'.$user_id.'%'];
        $user = db('user_recommend')->where($where)->select();
        foreach($user as $k=>$v){
          $id[] = $v['user_id']; 
        }
        $id = implode(',', $id);
        echo $id;
    }
    public function deluser(){
        $user_id = input('user_id');
        $where['id'] = ['in',$user_id];
        $data['del'] =2;
        $data['delete_time'] =1539747154;
        $r = db('user')->where($where)->update($data);
        echo $r;
    }

    //修改天使币价格
    public function uptsprice(){
        //获取天使币最新价格
        $price = db('tsprice')->order('addtime desc')->find();
        //增加一条新数据
        $data['price'] = $price*config('site.tspeice_fee');
        $data['addtime'] = time();
        $r = db('tsprice')->insert($data);
        $this->success('修改成功');
    }
}

